<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 15-6-4
 * Time: 上午11:00
 */
namespace Wechat\Controller;


class OrderController extends BaseController{
    /***订单列表***/
    public function olist(){
        if(!session('wcInfo')) {
            showTips('/index.php?s=/Wechat/Index/signin.html',"需要登录才能操作，微信自动登录中");
        }

        $userInfo = session('wcInfo');
        $query = empty($_GET["query"]) ? 0 : I("query");
        $where = "issh=1 AND uid=".$userInfo["id"];
        switch($query){
            case 1:
                $where .= " AND paystatu=0";
                break;
            case 2:
                $where .= " AND paystatu=1 AND expressstatu=1 ";
                break;
        }

        $myorder = M('order')->field("id,tradeno,paystatu,expressstatu")->where($where)->order("tradeno desc,id desc")->select();
        $olist = array();
        foreach($myorder as $k=>$v){
            $orderExt = M('order_ext')->where("oid=".$v["id"])->order("id desc")->select();
            switch($v['paystatu']){
                case 0:
                    $v["orderState"] = "待付款";
                    break;
                case 1:
                    $v["orderState"] = 0 == $v['expressstatu'] ? "待发货" : (1 == $v['expressstatu'] ? "已发货" : "已收货");
                    break;
                default:
                    $v["orderState"] = "";
                    break;
            }
            $v["orderExt"] = $orderExt;
            $olist[] = $v;
        }
        $this->assign('query',$query);
        $this->assign('olist',$olist);
        $this->display();
    }

    /***订单详情***/
    public function info(){
        if(!session('wcInfo')) {
            showTips('/index.php?s=/Wechat/Index/signin.html',"需要登录才能操作，微信自动登录中");
        }

        $userInfo = session('wcInfo');
        $id = empty($_GET["id"]) ? 0 : I("id");

        $where = "issh=1 AND uid=".$userInfo["id"]." AND id=".$id;
        $myorder = M('order')->where($where)->order("tradeno desc,id desc")->select();
        !$myorder && showTips('?s=/Wechat/Order/olist.html','该订单无效');
        foreach($myorder as $k=>$v){
            $orderExt = M('order_ext')->where("oid=".$v["id"])->order("id desc")->select();
            switch($v['paystatu']){
                case 0:
                    $v["orderState"] = "待付款";
                    break;
                case 1:
                    $v["orderState"] = 0 == $v['expressstatu'] ? "待发货" : (1 == $v['expressstatu'] ? "已发货" : "已收货");
                    break;
                default:
                    $v["orderState"] = "";
                    break;
            }
            $v["orderExt"] = $orderExt;
            $olist[] = $v;
        }

        $whereAddrid = "uid=".$userInfo['id'];
        0 < $addrid && $whereAddrid .= " AND id=".$addrid;
        $address = M("address")->where($whereAddrid)->order("isdefault desc,id desc")->find();
        if( $address ){
            $isSubmit = true;
            M('order')->where(" id in(".$orderIds.")")->save(array("addrid"=>$address["id"]));
            $addressLink = array("url"=>"/index.php?s=/Wechat/My/address.html&a_select=".$address["id"],"title"=>"修改收货地址");
        } else {
            $addressLink = array("url"=>"/index.php?s=/Wechat/My/address_add.html&a_select=0","title"=>"添加收货地址");
        }

        $this->assign('address',$address);
        $this->assign('addressLink',$addressLink);
        $this->assign('query',$query);
        $this->assign('olist',$olist);
        $this->display();
    }

    /***删除订单***/
    public function del(){
        if(!session('wcInfo')) {
            showTips('/index.php?s=/Wechat/Index/signin.html',"需要登录才能操作，微信自动登录中");
        }

        $userInfo = session('wcInfo');
        $id = empty($_GET["id"]) ? 0 : I("id");
        chkTimeDoAction(time(),5,'/index.php?s=/Wechat/Order/olist.html');

        $where = "paystatu=0 AND issh=1 AND uid=".$userInfo["id"]." AND id=".$id;
        $myorder = M('order')->where($where)->find();
        !$myorder && showTips('/index.php?s=/Wechat/Order/olist.html','没有找到订单');
        $res = M('order')->where($where)->save(array("issh"=>0));
        if($res){
            setTimeDoAction(time());
            //$this->success('删除成功','/index.php?s=/Wechat/Order/olist.html',2);
            header("Location:/index.php?s=/Wechat/Order/olist.html");
            exit();
        }else{
            $this->error("操作失败");
        }

    }

    /***订单生成***/
    public function index(){
        if(!session('wcInfo')) {
            showTips('/index.php?s=/Wechat/Index/signin.html',"需要登录才能操作，微信自动登录中");
        }

        /***产品列表***/
        $userInfo = session('wcInfo');

        $send_request = $_SERVER['HTTP_REFERER'];
        $http_host    = $_SERVER['HTTP_HOST'];
        if ( "" == $send_request || "http://".$http_host."/index.php?s=/Wechat/Cart/index.html" !== $send_request ) {
            showTips('?s=/Wechat/Cart/index.html',"要在购物车中才能生成订单！");

        }

        $ids = isset($_POST["id"]) ? I("id") : 0; //商品ID
        $num = isset($_POST["num"]) ? I("num") : 0; //商品数量
        $promoterid = isset($_POST["promoterid"]) ? I("promoterid") : 0; //推客ID

        $whereAddrid = "uid=".$userInfo['id'];
        $address = M("address")->where($whereAddrid)->order("isdefault desc,id desc")->limit(0,5)->select();
        if( !$address ){
            header("Location:/index.php?s=/Wechat/My/address_add.html&goback=Cart");
            exit();
        }

        session("ORDER_SUBMIT_".$userInfo["id"]) && 10 > time() - session("ORDER_SUBMIT_".$userInfo["id"]) && showTips('?s=/Wechat/Cart/index.html',"不能重复提交！");


        $cookieName = 'CART_'.$userInfo["id"];
        !cookie($cookieName) && showTips('?s=/Wechat/Cart/index.html',"您的购物车已经没有商品了");

        (0 == $ids || 0 == $num) && showTips('?s=/Wechat/Cart/index.html',"您的购物还没有商品");
        $where = " id in(".implode($ids,",").")";

        $order_ext = array();
        $tradeno_tmp = time()."-".rand(100,999);
        //取出商家
        $provide = M('product')->field('provide_id')->group("provide_id")->where($where)->order("provide_id asc")->select();
        foreach($provide as $k=>$v){
            //按商家生成订单
            $tradeno = $tradeno_tmp."-".$v["provide_id"]; //订单ID
            $order = array(
                "tradeno"=>$tradeno,
                "prividerid"=>$v["provide_id"],
                "uid"=>$userInfo["id"],
                "addrid"=>0,
                "ctime"=>time(),
                "expressstatu"=>0,
                "paystatu"=>0,
                "express"=>"",
                "expressno"=>"",
                "totleprice"=>"",
                "issh"=>1,
                "bank_type"=>""
            );
            $oid = M("order")->add($order);
            if($oid){
                $where1 = $where." AND provide_id=". $v["provide_id"];
                $proList = M('product')->field('id,pro_name,img_order,left_stock,unit,sale_price,tuike_commistion,pingtai_commistion')->where($where1)->select();
                $all = array();
                $allMoney = 0;
                $totle_platformmon = 0;
                $totle_promon = 0;
                foreach($proList as $k1=>$v1){
                    $idx = getStrInArrayPostion($v1["id"],$ids);
                    $all["oid"] = $oid;
                    $all["pid"] = $v1["id"];
                    $all["pname"] = $v1["pro_name"];
                    $all["pprice"] = $v1["sale_price"];
                    $all["pnum"] = $num[$idx];
                    $all["img_order"] = $v1["img_order"];
                    $all["promoterid"] = $promoterid[$idx];
                    $all["unit"] = $v1["unit"];
                    $all["ctime"] = time();
                    $all["platform_money"] = $v1["pingtai_commistion"]*$num[$idx];
                    $all["promoter_money"] = $v1["tuike_commistion"]*$num[$idx];
                    $allMoney += $v1["sale_price"]*$num[$idx];
                    $totle_platformmon += $v1["pingtai_commistion"]*$num[$idx];
                    $totle_promon += $v1["tuike_commistion"]*$num[$idx];
                    $extId = M("order_ext")->add($all);
                }
                M("order")->where("id=".$oid)->save(array("totleprice"=>$allMoney,"totle_platformmon"=>$totle_platformmon,"totle_promon"=>$totle_promon));
            }

        }
        session("ORDER_SUBMIT_".$userInfo["id"],time()); //防止重复提交
        cookie($cookieName,null);   //清空购物车
        header("Location:/index.php?s=/Wechat/Order/payment.html");
    }
    /**购物车-订单付款页面**/
    public function payment(){
        if(!session('wcInfo')) {
            showTips('/index.php?s=/Wechat/Index/signin.html',"需要登录才能操作，微信自动登录中");
        }
        $userInfo = session('wcInfo');

        $allMoney = 0; //总价
        $allNum = 0; //商品总数量
        $isSubmit = false; //是否允许支付
        $mynewordert = M('order')->field("tradeno")->where("uid=".$userInfo["id"])->order("id desc")->find();
        !$mynewordert && header("Location:/index.php?s=/Wechat/Order/list.html");

        $tradeno_tmp = substr($mynewordert["tradeno"],0,14);
        $myorder = M('order')->field("id,addrid")->where("issh=1 AND paystatu=0 AND uid=".$userInfo["id"]." AND tradeno like '".$tradeno_tmp."-%'")->order("id desc")->select();
        $orderIds = "0";
        $addrid = 0;
        $isSetAddress = false; //是否修改地址
        foreach($myorder as $k=>$v){
            $orderIds .= ",".$v["id"];
        }

        $where1 = " oid in(".$orderIds.") ";
        $orderExt = M('order_ext')->where($where1)->select();

        //取出用户地址
        $whereAddrid = "uid=".$userInfo['id'];
        $address = M("address")->where($whereAddrid)->order("isdefault desc,id desc")->limit(0,5)->select();
        if( $address ){
            $isSubmit = true;
            //设置收货地址
            $addrid = $address[0]["id"]; //将默认地址设置为收货地址
            $addressInfo = $address[0]["province"]." ".$address[0]["city"]." ".$address[0]["area"]." ".$address[0]["address"];
            M('order')->where(" id in(".$orderIds.")")->save(array("addrid"=>$addrid,"username"=>$address[0]["username"],"mobile"=>$address[0]["mobile"],"address"=>$addressInfo,"code"=>$address[0]["code"]));
            $selAddress = $address[0];
            $addressLink = array("url"=>"editAddress","title"=>"修改收货地址");
        } else {
            $addressLink = array("url"=>"addAddress","title"=>"添加收货地址");
        }

        $this->assign('selAddress',$selAddress);
        $this->assign('resAddress',$address);
        $this->assign('addressLink',$addressLink);
        $this->assign('addrid',$addrid);
        $this->assign('orderList',$myorder);
        $this->assign('orderExt',$orderExt);
        $this->assign('isSubmit',$isSubmit);
        $this->display("index");
    }
    /**冲订单列表-进入订单付款页面**/
    public function paymentone(){
        if(!session('wcInfo')) {
            showTips('/index.php?s=/Wechat/Index/signin.html',"需要登录才能操作，微信自动登录中");
        }

        $addrid = empty($_GET["addrid"]) ? 0 : I('addrid');
        $oid = empty($_GET["id"]) ? 0 : I('id');
        $oid = is_array($oid) ? implode($oid,",") : $oid;

        $userInfo = session('wcInfo');
        $allMoney = 0; //总价
        $allNum = 0; //商品总数量
        $isSubmit = true; //是否允许支付


        $myorder = M('order')->field("id,addrid,username,mobile,address")->where("paystatu=0 AND uid=".$userInfo["id"]." AND id in(".$oid.")")->order("id desc")->select();
        !$myorder && header("Location:/index.php?s=/Wechat/Order/list.html");

        $where1 = " oid in(".$oid.") ";
        $orderExt = M('order_ext')->where($where1)->select();

        //取出用户地址
        $selAddress = array("username"=>$myorder[0]['username'],"mobile"=>$myorder[0]['mobile'],"address"=>$myorder[0]['address']);


        $this->assign('selAddress',$selAddress);
        $this->assign('resAddress',$address);
        $this->assign('addressLink',$addressLink);
        $this->assign('addrid',$addrid);
        $this->assign('orderList',$myorder);
        $this->assign('orderExt',$orderExt);
        $this->assign('isSubmit',$isSubmit);
        $this->display("index");
    }

    /***确认收货**/
    public function receipt(){
        chkPost();
        if(!session('wcInfo')) {
            showTips('/index.php?s=/Wechat/Index/signin.html',"需要登录才能操作，微信自动登录中");
        }
        $userInfo = session('wcInfo');

        $id = empty($_GET["id"]) ? 0 : I("id");
        0 == $id && showTips('/index.php?s=/Wechat/Order/olist.html','非法提交');

        chkTimeDoAction(time(),3,false);

        $myorder = M('order')->field("id")->where("uid=".$userInfo["id"]." AND id=".$id." AND paystatu=1 AND expressstatu=1")->find();
        !$myorder && showTips('/index.php?s=/Wechat/Order/olist.html','该订单不能确认收货');


        $res = M('order')->where("uid=".$userInfo["id"]." AND id=".$id." AND paystatu=1 AND expressstatu=1")->save(array("expressstatu"=>2));

        //vip 总消费额total_consumer
        //provider 总销售额sales_totle    总订单数totle_trade
        // yps_promoter  success_pro 成功推送 = totle_business历史总成单数  totle_money总金额 able_out 可提现金额增加//更据佣金来
        /*vip is start*/
        $orderinfo = M('order')->where(array('id'=>$id))->find();//找出订单信息
        if(!$orderinfo)exit();
        M('vip')->where(array('id'=>$userInfo["id"]))->setInc('total_consumer',$orderinfo['totleprice']);
        /*vip is end*/

        /*  provider is start */
        $providerid =  $orderinfo['prividerid'];
        M('provider')->where(array('id'=>$providerid))->setInc('sales_totle',$orderinfo['totleprice']);//销售总额 增加
        M('provider')->where(array('id'=>$providerid))->setInc('totle_trade',$orderinfo['totleprice']);//订单总数增加 增加
        /* provider is end */

        /*promoter is  start*/
        //查找改订单小的 所有产品
        $ext_info = M('order_ext')->where(array('oid'=>$id))->select();//查询出所有产品
        //foreach 重构
        $promoter_num = null;
        $money = null;
        $yongjin = null;
        /*产品相关
           sales_num  商品历史销售量
           commistion_totle 历史发放佣金总额
           sales_totle 历史销售总额
           platform_totle  历史发放平台佣金总额
           pro_order_num订单总数

        */
        $salesNum = null;
        $money_promoter = null;
        $money_platform = null;
        $history_sale = null;
        $history_totle = null;
        /*成交单数*/
        $totle_business = null;
        $un_deal_totle = 0;
        foreach($ext_info as $row){
            //总计此订单 给供应商产生多少未结算金额
            if($row['promoter_money'] || $row['promoter_money']){
                $un_deal_totle += $row['pprice']*$row['pnum'] - ($row['promoter_money']+$row['promoter_money'])*$row['pnum'];
            }
            if($row['pid']){
                if($salesNum[$row['pid']]){
                    $salesNum[$row['pid']] += $row['pnum'];
                }else{
                    $salesNum[$row['pid']] = $row['pnum'];
                }
                /*end of salenum*/
                if($money_promoter[$row['pid']]){
                    $money_promoter[$row['pid']] += $row['promoter_money']*$row['pnum'];
                }else{
                    $money_promoter[$row['pid']] = $row['promoter_money']*$row['pnum'];
                }
                /*end  of money_promoter*/
                if($money_platform[$row['pid']]){
                    $money_platform[$row['pid']] += $row['money_platform']*$row['pnum'];
                }else{
                    $money_platform[$row['pid']] = $row['money_platform']*$row['pnum'];
                }
                /*end of the money_platform*/
                if($history_sale[$row['pid']]){
                    $history_sale[$row['pid']] += $row['pprice']*$row['pnum'];
                }else{
                    $history_sale[$row['pid']] = $row['pprice']*$row['pnum'];
                }
                /* end of the history sales totle*/
                if($history_totle[$row['pid']]){
                    $history_totle[$row['pid']] += 1;
                }else{
                    $history_totle[$row['pid']] = 1;
                }
                /*end of the totle order counts*/
            }

            //此订单关联的推客ID
            if($row['promoterid']){
                $totle_business[$row['promoterid']] = 1;

                if($promoter_num[$row['promoterid']]){
                    $promoter_num[$row['promoterid']] += 1;
                }else{
                    $promoter_num[$row['promoterid']] = 1;
                }

                //记录推客 推送成交金额变化 //推客总销售金额
                if($row['pnum']*$row['pprice'] != 0){
                    if($money[$row['promoterid']]){
                        $money[$row['promoterid']] += $row['pnum']*$row['pprice'];
                    }else{
                        $money[$row['promoterid']] = $row['pnum']*$row['pprice'];
                    }
                }
                //维护推客 佣金 平台和产品 放一起
                if(($row['promoter_money'])){
                    if($money[$row['promoterid']]){
                        $yongjin[$row['promoterid']] += $row['promoter_money']*$row['pnum'];
                    }else{
                        $yongjin[$row['promoterid']] = $row['promoter_money']*$row['pnum'];
                    }
                }
            }
            //产品相关
        }
        //处理供应商为结算金额
        if($un_deal_totle)M('provider')->where(array('id'=>$providerid))->setInc('un_deal_totle',$un_deal_totle);
        // 成功推送
        if($promoter_num){
            foreach($promoter_num as $key => $row){
                M('promoter')->where(array('aid'=>$key))->setInc('success_pro',$row);//推广者 成单数量增加
            }
        }
        //总金额 和 可提现金
        foreach($yongjin as $key => $row){
            M('promoter')->where(array('aid'=>$key))->setInc('totle_money',$row);//可提佣金
            M('promoter')->where(array('aid'=>$key))->setInc('able_out',$row);//历史总佣金
        }
        if($totle_business){
            foreach($totle_business as $key => $row){
                M('promoter')->where(array('aid'=>$key))->setInc('totle_business',$row);//可提佣金
            }
        }
        /*promoter is  end*/

        /*product is start*/
        /* sales_num  商品历史销售量
           commistion_totle 历史发放佣金总额
           sales_totle 历史销售总额
           platform_totle  历史发放平台佣金总额
           pro_order_num订单总数
           promoteNum 推广量
        */

        if($salesNum){
            foreach($salesNum as $key => $row){
                //历史商品销售量
                M('product')->where(array('id'=>$key))->setInc('sales_num',$row);
            }
        }
        if($money_promoter){
            foreach($money_promoter as $key => $row){
                //历史推客佣金发放
                M('product')->where(array('id'=>$key))->setInc('commistion_totle',$row);
            }
        }
        if($money_platform){
            foreach($money_platform as $key => $row){
                //历史平台佣金发放
                M('product')->where(array('id'=>$key))->setInc('platform_totle',$row);
            }
        }
        if($history_sale){
            foreach($history_sale as $key => $row){
                //历史平台佣金发放
                M('product')->where(array('id'=>$key))->setInc('sales_totle',$row);
            }
        }

        if($history_totle){
            foreach($history_totle as $key => $row){
                //历史平台佣金发放
                M('product')->where(array('id'=>$key))->setInc('pro_order_num',$row);
            }
        }
        setTimeDoAction(time());
        /*product is  end */
        $res ? /*$this->success('已确认收货','/index.php?s=/Wechat/Order/olist/query/2.html',2)*/header("Location:/index.php?s=/Wechat/Order/olist/query/2.html") : $this->error("操作失败");

        //$res ? /*$this->success('已确认收货','/index.php?s=/Wechat/Order/olist/query/2.html',2)*/header("Location:/index.php?s=/Wechat/Order/olist/query/2.html") : $this->error("操作失败");

    }
}